package com.changgou.system.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;

/*
    GlobalFilter为请求业务以及路由的URI转换为真实业务服务的请求地址的核心过滤器，
    不需要配置，模式系统初始化时加载，并作用在每个路由上
 */
@Component
public class IpFilter implements GlobalFilter, Ordered {
    /*
        过滤内容
        ServerWebExchange是一个HTTP请求-响应交互的契约。提供对HTTP请求和响应的访问，
        并公开额外的服务器端处理相关属性和特性，如请求属性。
        GatewayFilterChain 表示网关过滤链表，用于过滤器的链式调用
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("经过第1个过滤器IpFilter");
        ServerHttpRequest request = exchange.getRequest();
        InetSocketAddress remoteAddress = request.getRemoteAddress();
        System.out.println("ip地址："+remoteAddress.getHostName());
        return chain.filter(exchange);//过滤器链调用exchange执行拦截
    }
    //优先级，值越高，优先级越低
    @Override
    public int getOrder() {
        return 1;
    }
}
